from django import  forms
from django.contrib.auth.hashers import check_password

from user.models import User


class RegisterVerifyForm(forms.Form):
    user_name = forms.CharField(required=True,error_messages={
        'required':'用户名必填'
    })
    pwd = forms.CharField(required=True,error_messages={
        'required':'密码必填'
    })
    cpwd = forms.CharField(required=True,error_messages={
        'required':'确认密码必填'
    })
    email = forms.CharField(required=True, error_messages={
        'required': '邮箱必填'
    })
    def clean(self):
        pwd = self.cleaned_data.get('pwd')
        cpwd = self.cleaned_data.get('cpwd')
        user = User.objects.filter(username=self.cleaned_data.get('user_name'))
        if user:
            raise forms.ValidationError({'user_name':'该用户名已经被注册了'})
        if pwd != cpwd:
            raise forms.ValidationError({'cpwd':'两次输入的密码不一致'})
        return self.cleaned_data

class LoginVerifyForm(forms.Form):
    username = forms.CharField(required=True,error_messages={
                                'required':'用户名必填'
                                })
    pwd = forms.CharField(required=True,error_messages={
                                'required':'密码必填'
                                })
    def clean(self):
        user = User.objects.filter(username=self.cleaned_data.get('username')).first()
        if not user:
            raise forms.ValidationError({'username':'该账户不存在'})
        if check_password(user.password ,self.cleaned_data.get('pwd')):
            # 此时的user.password已经加密了，值为hash值
            raise forms.ValidationError({'pwd':'用户名或者密码不正确'})
        return self.cleaned_data